package com.example.service.utils;

import com.alibaba.fastjson.JSONObject;

import com.example.common.constant.Constants;
import com.example.common.enums.ImConnectStatusEnum;
import com.example.common.model.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description:获取userseesion的工具类
 * @author 易寸天
 * @version: 1.0
 */
@Component
public class UserSessionUtils {

    public Object get;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //1.获取用户所有的session
    public List<UserSession> getUserSession(Integer appId, String userId){

        String userSessionKey = appId + Constants.RedisConstants.UserSessionConstants
                + userId;
        Map<Object, Object> entries =
                stringRedisTemplate.opsForHash().entries(userSessionKey);
        List<UserSession> list = new ArrayList<>();   //存的是在线session
        Collection<Object> values = entries.values();
        for (Object o : values){    //将所有的session取出 进行判断
            String str = (String) o;
            UserSession session =
                    JSONObject.parseObject(str, UserSession.class);
            if(session.getConnectState() == ImConnectStatusEnum.ONLINE_STATUS.getCode()){     //判断这个session是不是在线状态
                list.add(session);    //如果在线就添加到里面去
            }
        }
        return list;    //返回所有在线的session
    }


    //2.获取除本端的session



    //这里获取指定端的session
    public UserSession getUserSession(Integer appId,String userId
            ,Integer clientType,String imei){

        String userSessionKey = appId + Constants.RedisConstants.UserSessionConstants
                + userId;
        String hashKey = clientType + ":" + imei;    // 通过这个获取到
        Object o = stringRedisTemplate.opsForHash().get(userSessionKey, hashKey);
        UserSession session =
                JSONObject.parseObject(o.toString(), UserSession.class);
        return session;
    }


}
